package com.hk.Mgr.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hk.commons.enm.MicroServiceType;
import com.hk.commons.enm.OperationEvent;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.IPUtil;
import com.hk.commons.vo.OperationLogDTO;
import com.hk.service.OperationLogService;
import com.hk.service.sys.ISysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hk.Mgr.web.message.kyc.UserPaymentDetailReq;
import com.hk.app.utils.ExcelService;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.CardStatusCode;
import com.hk.commons.ConstantRoute;
import com.hk.commons.HqlFilter;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.product.HistoryPayment;
import com.hk.service.IOrganization;
import com.hk.service.order.IHistoryPayment;
import org.springframework.web.client.RestTemplate;

/**
 * @author hk
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/userCardDetailCtr")
public class UserCardDetailCtr {	
	private Logger logger = LoggerFactory.getLogger(UserCardDetailCtr.class);
	
	@Autowired
	private IHistoryPayment historyPaymentService;
	
	@Autowired
	private IOrganization orgService;
	
	@Autowired
	private  JdbcTemplate jdbcTemplate;

	@Autowired
	private ISysUser userService;

	@Value("${payServer.baseUrl}")
	private String payServerUrl;

	@Autowired
	private OperationLogService operationLogService;
	
	@RequestMapping(value = "/excel",method = RequestMethod.GET)
	@ResponseBody
	public void excelExport(@RequestParam String userNameOrPhone,String finRealName,String channel, HttpServletResponse response) {		
		logger.info("导出关键参数userNameOrPhone={},finRealName={},channel={}",userNameOrPhone,finRealName,channel);
	
		List<Map<String, Object>> qryMapList = jdbcTemplate.queryForList(getSql(userNameOrPhone,finRealName,StringHelper.isEmpty(channel)?null:Integer.parseInt(channel),false));
		LinkedHashMap<String, String> struct = new LinkedHashMap<>();
	    struct.put("userPhone", "用户手机号");
	    struct.put("userRealName", "用户姓名");
	    struct.put("finPhone", "理财师手机号码");
	    struct.put("finRealName", "理财师姓名");
	    struct.put("supportCompany", "绑卡渠道(富友,火柴,盈米|1:富友绑卡3:火柴绑卡4:盈米绑卡|其余都是非绑卡状态）)");
	    struct.put("bankName", "银行名称");
	    struct.put("paymentNo", "银行卡号");
	    struct.put("status","换卡状态（0：失败，1：成功）");
	    struct.put("failMsg","失败原因");
	    struct.put("userOrgName", "所属部门");
		struct.put("subBankName", "银行分行名称");
	    ExcelService excelService = new ExcelService(qryMapList, struct);
	    String title = "绑卡统计列表";
	    excelService.exportToStream(response, title);	    
	}
	
	
	private String getSql(String userNameOrPhone,String finRealName,Integer channel,boolean ifAddLimit){
		StringBuilder sql=new StringBuilder("select * from paymentLookView where 1=1 ");
		if(StringHelper.isNotEmpty(userNameOrPhone)){
			sql.append("and (userRealName like '%"+userNameOrPhone+"%' or userPhone like '%"+userNameOrPhone+"%')");
		}
		if(StringHelper.isNotEmpty(finRealName)){
			sql.append(" and finRealName like '%"+finRealName+"%'");
		}
		if(channel!=null){
			sql.append(" and channel="+channel);
		}	
		sql.append(" order by operateCts desc");
		if(ifAddLimit){
			sql.append(" limit ?,?");
		}
		logger.info("getSql: " + sql);
		return sql.toString();
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<Map<String, Object>>> list(@RequestBody UserPaymentDetailReq req) {
		ResponseBase<List<Map<String, Object>>> responseBase=new ResponseBase<List<Map<String,Object>>>();
		try {
			String userNameOrPhone=req.getUserNameOrPhone();		
			String finRealName=req.getFinRealName();		
			Integer channel=req.getChannel();		
			int curPage=req.getCurPage();
			int pageSize=req.getPageSize();		
			logger.info("查询绑卡统计关键参数userNameOrPhone={},finRealName={},channel={},curPage={},pageSize={}",userNameOrPhone,finRealName,channel,curPage,pageSize);
			List<Map<String, Object>> qryMapList=jdbcTemplate.queryForList(getSql(userNameOrPhone,finRealName,channel,true),new Object [] {(curPage-1)*pageSize,pageSize});			
			for(Map<String, Object> map:qryMapList){
				if(map.get("supportCompany")!=null){
					String supportCompany=(String)map.get("supportCompany");
					String[] companys = supportCompany.split(",");
					map.put("fyCard", (companys[0].equals(ConstantRoute.COMPANY_HUAKANG+"")||companys[0].equals(CardStatusCode.FY_CHANGE_CARDING+""))?"是":"否");
					map.put("hcCard", companys[1].equals(ConstantRoute.COMPANY_HUOCHAI+"")?"是":"否");
					map.put("ymCard", companys[2].equals(ConstantRoute.COMPANY_YINGMI+"")?"是":"否");
					StringBuilder returnCompanies=new StringBuilder();
					String[] companies=supportCompany.split(",");
					if(String.valueOf(CardStatusCode.PAYMENT_DISPLAY_SHOW).equals(companies[0])||String.valueOf(CardStatusCode.FY_CHANGE_CARDING).equals(companies[0])){
						returnCompanies.append(ConstantRoute.COMPANY_HUAKANG_STR+",");
					}
					if(String.valueOf(ConstantRoute.COMPANY_HUOCHAI).equals(companies[1])){
						returnCompanies.append(ConstantRoute.COMPANY_HUOCHAI_STR+",");
					}
					if(String.valueOf(ConstantRoute.COMPANY_YINGMI).equals(companies[2])){
						returnCompanies.append(ConstantRoute.COMPANY_YINGMI_STR+",");
					}
					if(returnCompanies.length()>0){
						returnCompanies.setLength(returnCompanies.length()-1);							
					}					
					map.replace("supportCompany", returnCompanies.length()>0?returnCompanies:"无");
				}else{
					map.put("fyCard","否");
					map.put("hcCard","否");
					map.put("ymCard","否");
				}
				
				if(map.get("userOrgName")==null){
					map.replace("userOrgName", "无主客户部");
				}
				if(map.get("paymentId")!=null){
					map.replace("paymentId", ((Long)map.get("paymentId")).toString());
				}	
				if(map.get("userRealName")==null){
					map.replace("userRealName", "无");
				}
				if(map.get("paymentNo")==null){
					map.replace("paymentNo", "无");
				}
				if(map.get("finRealName")==null){
					map.replace("finRealName", "无");
				}
				if(map.get("finPhone")==null){
					map.replace("finPhone", "无");
				}
			}
			responseBase.setResultCode(ResultCode.SUCC.getCode());
			responseBase.setMsg(ResultCode.SUCC.getMsg());
			responseBase.setResult(qryMapList);
		} catch (Exception e) {
			logger.error("查询绑卡统计异常!",e);
			responseBase.setResultCode(ResultCode.FAILED.getCode());
			responseBase.setMsg(ResultCode.FAILED.getMsg());
			responseBase.setResult(null);
		}		
		return responseBase;
	}
	
	@RequestMapping(value = "/count", method = RequestMethod.POST)
	@ResponseBody
	public int count(@RequestBody UserPaymentDetailReq req) {
		int resultSize=0;
		String userNameOrPhone=req.getUserNameOrPhone();		
		String finRealName=req.getFinRealName();		
		Integer channel=req.getChannel();	
		StringBuilder sql=new StringBuilder("select count(1) from paymentDetailView where 1=1 ");
		if(StringHelper.isNotEmpty(userNameOrPhone)){
			sql.append("and (userRealName like '%"+userNameOrPhone+"%' or userPhone like '%"+userNameOrPhone+"%')");
		}
		if(StringHelper.isNotEmpty(finRealName)){
			sql.append("and finRealName like '%"+finRealName+"%'");
		}
		if(channel!=null){
			sql.append("and channel="+channel);
		}		
		try {
			resultSize=jdbcTemplate.queryForObject(sql.toString(), Integer.class);
		} catch (Exception e) {
			logger.info("<----------------------ERROR--------------------->");
			logger.error("查询总数异常！",e);
		}
		return resultSize;
	}
	
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/viewOneDetail", method = RequestMethod.GET)
	@ResponseBody
	public Map viewOneDetail(@RequestParam String paymentId) {
		Map<String, Object> map=new HashMap<>();
		List<HistoryPayment> resultList=new ArrayList<HistoryPayment>();
		HqlFilter filter=new HqlFilter();
		filter.addEQFilter("paymentId", Long.valueOf(paymentId));
		filter.addOrder("desc");
		filter.addSort("cts");
		String ymBindTime=null;
		String hcBindTime=null;
		String fyBindTime=null;	
		try {
			resultList=historyPaymentService.findByFilter(filter);
			for(int i=0;i<resultList.size();i++){
				HistoryPayment historyPayment=resultList.get(i);
				String paymentType=historyPayment.getPaymentType();			
				if(CardStatusCode.PAYMENT_TYPE_ADD.equals(paymentType)||CardStatusCode.PAYMENT_TYPE_CHANGE.equals(paymentType)){
				int company=resultList.get(i).getCompany(); 
				String operateCts=historyPayment.getVisibleCts(); 
				switch (company) {
					case ConstantRoute.COMPANY_HUAKANG:
						if(fyBindTime==null){fyBindTime=operateCts;}					
						break;
					case ConstantRoute.COMPANY_HUOCHAI:
						if(hcBindTime==null){hcBindTime=operateCts;}					
						break;
					case ConstantRoute.COMPANY_YINGMI:
						if(ymBindTime==null){ymBindTime=operateCts;}					
						break;
					default:
						break;
					}			
				}
			}
			map.put("ymBindTime", ymBindTime==null?"无":ymBindTime.toString());
			map.put("hcBindTime", hcBindTime==null?"无":hcBindTime.toString());
			map.put("fyBindTime", fyBindTime==null?"无":fyBindTime.toString());	
		} catch (Exception e) {
			logger.info("----------------查看卡号详细信息----------------paymentId={}",paymentId);
			logger.error("查看卡号详细信息!",e);
		}
		return map;
	}
	
	@RequestMapping(value = "/viewHistory", method = RequestMethod.GET)
	@ResponseBody
	public List<HistoryPayment> viewHistory(@RequestParam String paymentId) {
		if("null".equals(paymentId)){
			return null;
		}
		List<HistoryPayment> resultList=new ArrayList<HistoryPayment>();
		HqlFilter filter=new HqlFilter();
		filter.addEQFilter("paymentId", Long.valueOf(paymentId));
		try {
			resultList=historyPaymentService.findByFilter(filter);			
		} catch (Exception e) {
			logger.info("-----------------查询解绑/换卡信息异常!---------------paymentId={}",paymentId);
			logger.error("查询解绑/换卡信息异常!",e);
		}//399206960532884030
		return resultList;
	}

	/**
	 * 同步富友换卡信息
	 * @param actUserId
	 * @return
	 */
	@RequestMapping(value = "/syncBindCardAll", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<String> syncBindCardAll(HttpServletRequest request,Long actUserId){
		ResponseBase<String> result = new ResponseBase<>();
		SysUser user = userService.findById(actUserId);
		if (user == null){
			result.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
			result.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
		}
		String syncCardUrl = payServerUrl+"payServer/app/sync/syncBindCardAll";
		RestTemplate template = new RestTemplate();

		try {
			template.getForObject(syncCardUrl,String.class);
			result.setResult(ResultCode.SUCC.getMsg());
			result.setResultCode(ResultCode.SUCC.getCode());
		}catch (Exception e){
			result.setMsg(ResultCode.FAILED.getMsg());
			result.setResultCode(ResultCode.FAILED.getCode());
			logger.error("同步换卡信息失败！",e);
		}
		addSyncBindCardLog(request,actUserId);
		return result;
	}

	/**
	 * 增加同步信息操作记录
	 * @param actUserId
	 */
	private void addSyncBindCardLog(HttpServletRequest request,Long actUserId){
		JSONObject json = new JSONObject();
		json.put("actUserId",actUserId);

		OperationLogDTO log = new OperationLogDTO();
		log.setEvent(OperationEvent.SYNC_BIND_CARD_ALL);
		log.setEventRequestJson(JSON.toJSONString(json, SerializerFeature.WriteMapNullValue));
		log.setOperatorId(Long.valueOf(actUserId));
		log.setTerminalIP(IPUtil.getIpAddr(request));

		operationLogService.addLog(log);

	}
}
